from shapely.geometry import Polygon
from shapely.geometry import LineString
from shapely.geometry import Point
from shapely.geometry import MultiPolygon
    
def rectangleIntersectVector(rect,vect): 
    '''judge whether a rectangle intersect a vector
    input: List rect: the rectangle's coordinate list, like [0,0,1,1]
           List vect: the vector's coordinate list, like [0,0,1,0,1,1,0,1,0,0]
    output: Boolean bool: the boolean value for indicating whether the rectangle intersect the vector
    '''
    #tranform rectangle's coordinate list into vectgon's coordinate list
    if len(rect)==4:
        rect=transformRectangelToPolygon(rect)

    rectPoList=changeCoordFormat(rect)
    vectPoList=changeCoordFormat(vect)    
   
    #initialize the instance of Class vectgon in package shapely
    rectReal=Polygon(tuple(rectPoList))
    vectReal=LineString(tuple(vectPoList)) 
    
    #call intersects() in shapely to judge whether they two intersects
    if rectReal.intersects(vectReal):
        return True
    else:
        return False
    
def transformRectangelToPolygon(rect):
    '''tranform the rectangle's coordinate list format into a polygon's coordinate list format
    input: List rect: the rectangle's coordinate list, like [0,0,1,1]
    output: List poly: the transformed coordinate list, like [0,0,1,0,1,1,0,1,0,0]
    '''
    return [rect[0],rect[1],rect[0],rect[3],rect[2],rect[3],rect[2],rect[1]]

def changeCoordFormat(poly):
  #change the data format of the two coordinate lists, like from [0,0,1,0,1,1,0,1,0,0] to [[(0,0),(1,0),(1,1),(0,1),(0,0)] 
    coordList=[]
    i=0
    while i<len(poly):
        po1=(poly[i],poly[i+1])
        coordList.append(po1)
        i=i+2    
    return coordList

def reverseChangeCoordFormat(poly):
    coordList=[]
    for cd in poly:
        coordList.append(cd[0])
        coordList.append(cd[1])
    return coordList

def createBuffer(poly, dist):
    polyg=Polygon(changeCoordFormat(poly))
    polyBuff=polyg.buffer(dist)
    return polyBuff

def pointInPoly(pt,poly):
    return Point(pt).intersects(poly)


if __name__=='__main__':   
    print rectangleIntersectVector([0,0,1,1],[0,0,1,0])
    print createBuffer([0,0,1,0,1,1,0,1,0,0], 1)
    print pointInPoly((0.5, 0.5), Polygon(changeCoordFormat([0,0,1,0,1,1,0,1,0,0])))